package net.wesley.android.city;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import net.wesley.android.City;
import net.yebaihe.sdk.HttpConnection;

public class NanJing extends City {

	private Handler request1handler=new Handler(){
		public void handleMessage(Message message){
			switch (message.what){
			case HttpConnection.DID_ERROR://DID ERROR
				callback.onComplete(-1, "");
				break;
			case HttpConnection.DID_SUCCEED://DID SUCC
				String body=(String)message.obj;
				int index=body.indexOf("end_tr red'>");
				if(index>0){
					String msg=body.substring(index+12).split("</td>")[0];
					callback.onComplete(-10002, "ret:"+msg); 
				}
				else{
					String str=body;
					str=str.split("class=\"end_th\">处理状态")[1];
					str=str.split("</table>")[0];
					String[] rows=str.split("<tr");
					boolean firstrow=true;
					String retvalue="";
					for (int i=0;i<rows.length;i++){
						if (firstrow){
							firstrow=false;
							continue;
						}
						if (i==rows.length-1) break;//南京的特殊情况,最后一行不是
						String row=rows[i];
						String[] cols = row.split("<td");
						String shijian = cols[3].split(">")[1].split("</td")[0];
						String didian = cols[4].split(">")[1].split("</")[0];
						String code = cols[5].split(">")[1].split("</")[0];
						retvalue+=String.format("shijian:%s\ndidian:%s\ncode:%s\n\n",shijian,didian,code);
					}
					callback.onComplete(rows.length-2, retvalue);
				}
				break;
			}
		}
	};

	public void requestParamsFinish(String[] values) {
		try {
			String data=String.format("chexing=02&begindate=%s&keywords=%s&keywords2=%s&enddate=%s&fdjh=%s&newsearch=1&imageButton.x=32&imageButton.y=8",
					getBeginDate(),URLEncoder.encode("苏A","UTF-8"), chepai.substring(2), getEndDate(),values[0]);
			new HttpConnection(ctx,request1handler,"UTF-8").post("http://www.njjg.gov.cn/www/njjg/zxcx/bgcx.jsp", data);
			Log.d("myown", "post data:"+data);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	private String getEndDate() {
		Date d=new Date();
		return String.format("%d-%d-%d", d.getYear()+1900,d.getMonth()+1,d.getDate());
	}

	private String getBeginDate() {
		Date d=new Date();
		return String.format("%d-%d-%d", d.getYear()-1+1900,d.getMonth()+1,d.getDate());
	}

	@Override
	public boolean match(String chepai) {
		return chepai.startsWith("苏A");
	}

	@Override
	public String[] paramDesc() {
		String[] s={"发动机号后四位"};
		return s;
	}

}
